package graphics.fingerprint;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ImagePuller{
	
	private Socket socket;
	private Receiver receiver;
	private Handler handler;
	
	public ImagePuller(Handler handler){
		this.handler = handler;
	}
	
	public void startReceive(Socket s){
		this.socket = s;
		
		try {
			DataInputStream in = new DataInputStream(new BufferedInputStream(socket
					.getInputStream()));
			this.receiver = new Receiver(in);
			this.receiver.start();
		} catch (IOException e) {
			Log.d("Debug&Info", "receiver failed when start");
			e.printStackTrace();
		}
	}
	
	public void stopWork() throws IOException {
		if(receiver!=null&&receiver.isAlive()){
			this.receiver.stop();
		}
		this.socket.getInputStream().close();
	}
	
	class Receiver extends Thread {
		private DataInputStream dis;

		public Receiver(DataInputStream in) {
			this.dis = in;
		}

		@Override
		public void run() {
			while (!socket.isClosed()) {
				try {
					int msgSize = dis.readInt();
					byte[] buffer = new byte[msgSize];
					int length = 0;
					while (length < msgSize) {
						int readSize = dis.read(buffer, length, msgSize
								- length);
						if (readSize > 0) {
							length = length + readSize;
						} else {
							break;
						}
					}
					ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
					sourcePrepared(bis);
				} catch (IOException e) {
					Log.e("Log&Info", e.getMessage());
					e.printStackTrace();
					System.exit(0);
				}
			}
		}
	}
	
	private void sourcePrepared(final InputStream is) {
		Thread t = new Thread() {
			public void run() {
				Bitmap bitmap = decodeMsg(is);
				Message message = Message.obtain();
				message.what = PaintView.SOURCEPREPARED_PIC;
				message.obj = bitmap;
				handler.sendMessage(message);
			}
		};
		t.start();
	}

	private Bitmap decodeMsg(InputStream is) {
		Bitmap bmp = BitmapFactory.decodeStream(is);
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// DisplayMetrics dm =
		// SystemInfo.getDisplayMetrics(host.getView().getContext());
		return Bitmap.createScaledBitmap(bmp, (int) (bmp.getWidth()),
				(int) (bmp.getHeight()), true);
	}
}
